﻿// SwaggerServiceExtend.cs
// Copyright (c) 2022 chenchao
// Email:cc@on8.top

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.OpenApi.Models;
using OnWork.Tools.Swagger;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using Swashbuckle.AspNetCore.SwaggerUI;
using System;
using System.Collections.Generic;
using System.Text;

namespace Microsoft.Extensions.DependencyInjection
{

    /// <summary>
    /// Swagger 服务扩展
    /// </summary>
    public static class SwaggerServiceExtend
    {
        /// <summary>
        /// AddSwaggerGen 注册Swagger 
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration">配置文件注入,用于读取appSettings的配置</param>
        /// <param name="swaggerGenOptionsAction">配置委托可自定义配置</param>
        public static IServiceCollection AddSwaggerGenOnWork(this IServiceCollection services, IConfiguration configuration, Action<SwaggerGenOptions> swaggerGenOptionsAction=null)
        {
            //读取选项
            var Options = configuration.GetSection(SwaggerSettingsOptions.SwaggerSettings).Get<SwaggerSettingsOptions>();
            
            //初始化配置
            SwaggerSettings.Init(Options);

            //如果不配置则不启用
            if (SwaggerSettings.SettingsOptions.Enable != true) {
                return services;
            }
            services.AddSwaggerGen(x => SwaggerSettings.SwaggerGen(x, swaggerGenOptionsAction));
            return services;
        }


        /// <summary>
        ///  配置 UseSwagger UseSwaggerUI
        /// </summary>
        /// <param name="app"></param>
        /// <param name="swaggerOptionsAction">UseSwagger 自定义配置</param>
        /// <param name="swaggerUIOptionsAction">UseSwaggerUI 自定义配置</param>
        /// <returns></returns>
        public static IApplicationBuilder UseSwaggerAndUIOnWork(this IApplicationBuilder app, Action<SwaggerOptions> swaggerOptionsAction=null, Action<SwaggerUIOptions> swaggerUIOptionsAction=null)
        {
            //如果不配置则不启用
            if (SwaggerSettings.SettingsOptions.Enable != true) return app;

            //生成接口文件
            app.UseSwagger(options => SwaggerSettings.UseSwagger(options, swaggerOptionsAction));
            // 生成Web页面
            app.UseSwaggerUI(options => SwaggerSettings.UseSwaggerUI(options, swaggerUIOptionsAction));
            return app;
        }
    }
}
